<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Api\Service\Qrcode\Controllers;

use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\Qrcode;
use App\Eloquent\Ygt\QrcodeLog;
use App\Eloquent\Ygt\Stock;
use App\Eloquent\Ygt\StockIn;
use Framework\BaseClass\Api\Controller;
use App\Engine\Func;

class ProductController extends Controller
{
    public $userId          = 25;

    public function lists()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $qrcodeStr          = request('qrcode','');
        if(!$userInfo || !$qrcodeStr)
        {
            xThrow( ERR_PARAMETER );
        }
        $qrcodeStrList      = explode(',',$qrcodeStr);
        $qrcodeIdArr        = [];
        foreach($qrcodeStrList as $key=>$val)
        {
            $qrcodeArr          = explode('-',$val);
            $size               = count($qrcodeArr);
            if($size != 3)
            {
                continue;
            }
            $qrcodeId           = $qrcodeArr[1];
            $qrcodeIdArr[]      = $qrcodeId;
        }
        $lists                  = [];
        if(!empty($qrcodeIdArr))
        {
            //根据不同角色取不同表和模型
            $tableArr           = Func::getQrocdeTableArr($userInfo);
            $qrcodeModel        = $tableArr['qrcode_model'];
            $qrcodeFieldsModel  = $tableArr['fields_model'];
            $qrcodeLogModel     = $tableArr['log_model'];

            $where              = ['id'=>['in',$qrcodeIdArr]];
            $qrcodeList         = $qrcodeModel::getList($where);
            $productIdArr       = [];
            foreach($qrcodeList as $key=>$val)
            {
                $productIdArr[]     = $val->product_id;
            }
            //取列表
            $where              = ['ygt_product.id'=>['in',$productIdArr]];
            $productList        = Product::getListByJoin($where)->toArray();
            //取材料的自定义属性值
            $where              = ['product_id'=>['in',$productIdArr]];
            $customFieldsArr    = ProductFields::getTransformListToArr($where);
            //转换列表
            $otherArr           = ['custom_fields_arr'=>$customFieldsArr];
            $productList        = Product::transformListByType($productList,$otherArr);
            $productListArr     = [];
            foreach($productList as $key=>$val)
            {
                $productListArr[$val['id']] = $val;
            }
            //有可能不同二维对应同一个产品信息
            $tempQrcodeIdArr    = [];
            foreach($qrcodeList as $key=>$val)
            {
                $qrcodeId       = $val['id'];
                if(!in_array($qrcodeId,$tempQrcodeIdArr))
                {
                    $tempQrcodeIdArr[]  = $qrcodeId;
                    $productId  = $val['product_id'];
                    if(isset($productListArr[$productId]))
                    {
                        $temp       = $productListArr[$productId];
                        $temp['qrcode_id']  = $qrcodeId;
                        $lists[]    = $temp;
                    }
                }
            }
        }
        return $lists;
    }

    //出库
    public function out()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $qrcodeIdStr        = request('qrcode_ids','');
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $companyId          = $userInfo->company_id;
        $qrcodeIdArr        = explode(',',$qrcodeIdStr);
        foreach($qrcodeIdArr as $key=>$val)
        {
            if(!$val)
            {
                unset($qrcodeIdArr[$key]);
            }

        }
        $number             = count($qrcodeIdArr);
        if($number == 0)
        {
            return [
                'code' => 1,
                'message' => '请勾选出库材料',
            ];
//            xThrow( ERR_PARAMETER,'请勾选出库材料' );
        }

        //增加限制，不能多次出库 zhuyujun 20181115
        foreach($qrcodeIdArr as $key=>$val)
        {
            $tmpQrcodeLogList =  \App\Eloquent\Ygt\QrcodeLog::where(['qrcode_id'=>$val,'type'=>1])->get();

            foreach ($tmpQrcodeLogList as $tmpQrcodeLogRow){
                $tmpTableId = $tmpQrcodeLogRow['table_id'];
                $tmpStockRow = \App\Eloquent\Ygt\Stock::where(['id'=>$tmpTableId])->first();
                if($tmpStockRow['relate_type'] == 6){
                    return [
                        'code' => 1,
                        'message' => '请勿重复出库',
                    ];
                }

            }
        }



        //根据不同角色取不同表和模型
        $tableArr           = Func::getQrocdeTableArr($userInfo);
        $logTable           = $tableArr['log_table'];
        $qrcodeModel        = $tableArr['qrcode_model'];
        $qrcodeFieldsModel  = $tableArr['fields_model'];
        $qrcodeLogModel     = $tableArr['log_model'];

        $where              = ['id'=>['in',$qrcodeIdArr]];
        $qrcodeList         = $qrcodeModel::getList($where);
        if(!$qrcodeList)
        {
            xThrow( ERR_PARAMETER,'二维码信息出错' );
        }
        $productId          = $qrcodeList[0]->product_id;

        //先统计总数量
        $qrcodeNowNumberAll = 0;
        foreach($qrcodeList as $key=>$val)
        {
            $valNowNumber   = $val->now_number;
            $qrcodeNowNumberAll += $valNowNumber;
        }




        //出库入表
        $addData = [
            'number'=>$qrcodeNowNumberAll,//出库流水数量（这个数量是错的）
            'material_id' => $productId,//材料ID
            'company_id' => $companyId,//企业ID
            'uid' => $userId,//用户ID
            'relate_type' => 6,//相关类型，现在可以固定 写2
            'relate_id' => 0,//外键ID，没有相关业务ID，写0
        ];
        $tableId            = \App\Engine\Stock::addOutgoingWater($addData);
        if($tableId === false)
        {
            xThrow(ERR_UNKNOWN,'出库失败');
        }
        $dataAll            = [];

        foreach($qrcodeList as $key=>$val)
        {
            $temp           = [
                'type'=>1,
                'qrcode_id'=>$val->id,
                'table_name'=>'ygt_stock',
                'table_id'=>$tableId,
                'number'=>$val->now_number,
            ];
            $dataAll[]      = $temp;
        }

        if(!empty($dataAll))
        {
            \DB::table($logTable)->insert($dataAll);

            //已经在流水中处理过数量不需要2次处理

            //更新材料的库存数量
//            $tmpProductObj = Product::where('id', $productId);
//            $tmpProductObj->decrement('number', $qrcodeNowNumberAll);

//            //更新集合材料的库存数量
//            $tmpProductRow = $tmpProductObj->first();
//            if($tmpProductRow['assemblage_material_id']){
//                $tmpAssemblageMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpProductRow['assemblage_material_id']])->first();
//                if($tmpAssemblageMaterialRow){
//                    $tmpAssemblageMaterialRow->number = $tmpAssemblageMaterialRow->number - $qrcodeNowNumberAll;
//                    $tmpAssemblageMaterialRow->save();
//                }
//            }

        }
        return ['message'=>'出库成功'];
    }
    //入库
    public function in()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $qrcodeIdsStr       = request('qrcode_ids','');
        $productId          = request('product_id','');
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        //根据不同角色取不同表和模型
        $tableArr           = Func::getQrocdeTableArr($userInfo);
        $qrcodeTable        = $tableArr['qrcode_table'];
        $qrcodeModel        = $tableArr['qrcode_model'];
        $qrcodeFieldsModel  = $tableArr['fields_model'];
        $qrcodeLogModel     = $tableArr['log_model'];

        $companyId          = $userInfo->company_id;
        $qrcodeIdArr        = explode(',',$qrcodeIdsStr);
        $where              = ['id'=>['in',$qrcodeIdArr]];
        $qrcodeList         = $qrcodeModel::getList($where);
        $idArr              = [];
        $stockNumber        = 0;
        $placeName = '';
        foreach($qrcodeList as $key=>$val)
        {
            $qrcodeId       = $val->id;
            $stockId        = $val->stock_id;
            $varProductId   = $val->product_id;
            $valTotalNumber = $val->total_number;
            $placeName     = $val->place_name;
            if($stockId > 0)
            {
                xThrow( ERR_PARAMETER,'已经使用过了'.$qrcodeId);
            }
            if($varProductId != $productId)
            {
                xThrow( ERR_PARAMETER,'二维码材料信息与入库材料信息不符'.$qrcodeId );
            }
            $idArr[]        = $qrcodeId;
            $stockNumber    += $valTotalNumber;
        }
        $updateResult       = false;
        if(!empty($idArr))
        {
            //需要和手动入库的逻辑保持一致-----------开始
            //入ygt_stock 表
            $where              = ['id'=>$productId];
            $product            = Product::getInfo($where);
            if(!$product)
            {
                xThrow(ERR_UNKNOWN,'材料信息出错');
            }
            //$placeName          = $product->place_name;
            $waterNo            = \App\Engine\Stock::createWaterNo();
            $relateType         = 7;
            $stockData          = [
                'company_id'=>$companyId,
                'water_no' => $waterNo,
                'relate_type' => $relateType,
                'relate_id' => 0,
                'product_id' => $productId,
                'number' => $stockNumber,
                'total_price' => 0,
                'operate_uid' => $userId,
                'remark' => '',
                'is_customer'=>0,
                'customer_id'=>0,
                'who_name'=>'',
                'place_name'=>$placeName,
            ];
            $lastProductNumber  = $product->number;
            $relateType         = \App\Engine\Stock::getRelateType($relateType);
            $stockData['type']          = $relateType['type'];
            $stockData['stock_type']        = $relateType['stock_type'];
            $stockData['last_product_number']       = $lastProductNumber + $stockNumber;
            $stockId            = Stock::insertOneData($stockData,'id');
            if($stockId===false)
            {
                xThrow(ERR_UNKNOWN,'入库失败');
            }

            //更新材料的库存数量
            $tmpProductObj = Product::where('id', $productId)->first();
            $tmpProductObj->increment('number', $stockNumber);

            //更新材料的计量属性
            $tmpProductObj = \App\Eloquent\Ygt\Product::where('id', $productId)->first();
            $materialComputeNum = \App\Engine\Material::getMaterialComputeNum($productId,$stockNumber);
            if($materialComputeNum){
                //获取计量属性字段
                $tmpProductFieldsList = \App\Eloquent\Ygt\ProductFields::where(['assemblage_material_id'=>$tmpProductObj['assemblage_material_id']])->get();
                foreach ($tmpProductFieldsList as $tmpProductFieldsRow){
                    if($tmpProductFieldsRow['is_compute']){
                        $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::firstOrNew(['material_id'=>$productId,'type'=>1,'product_fields_id'=>$tmpProductFieldsRow['id']]);
                        $tmpObj->number = $tmpObj->number + $materialComputeNum;
                        $tmpObj->save();
                    }
                }
            }


            //更新集合材料的库存数量
            $tmpProductRow = $tmpProductObj;
            if($tmpProductRow['assemblage_material_id']){
                $tmpAssemblageMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpProductRow['assemblage_material_id']])->first();
                if($tmpAssemblageMaterialRow){
                    $tmpAssemblageMaterialRow->number = $tmpAssemblageMaterialRow->number + $stockNumber;
                    $tmpAssemblageMaterialRow->save();

                    //更新集合材料的计量属性
                    if($materialComputeNum){
                        //获取计量属性字段
                        $tmpProductFieldsList = \App\Eloquent\Ygt\ProductFields::where(['assemblage_material_id'=>$tmpProductObj['assemblage_material_id']])->get();
                        foreach ($tmpProductFieldsList as $tmpProductFieldsRow){
                            if($tmpProductFieldsRow['is_compute']){
                                $tmpObj = \App\Eloquent\Ygt\ProductFieldsCompute::firstOrNew(['material_id'=>$tmpAssemblageMaterialRow['id'],'type'=>2,'product_fields_id'=>$tmpProductFieldsRow['id']]);
                                $tmpObj->number = $tmpObj->number + $materialComputeNum;
                                $tmpObj->save();
                            }
                        }
                    }

                }
            }


            //需要和手动入库的逻辑保持一致-----------结束
            //更新二维码对应的信息
            $data           = ['stock_id'=>$stockId];
            $updateResult   = \DB::table($qrcodeTable)->whereIn('id',$idArr)->update($data);
        }
        if($updateResult === false)
        {
            xThrow( ERR_PARAMETER,'入库失败');
        }
        return ['入库成功'];
    }
}